import { Badge } from "antd-mobile";
import { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import getApi from "../../result/api";
import '../../css/Message.scss'
function Message() {
   // 获取一个实时时间戳
   let Newtime = new Date().getTime();
   // 定义一个函数将时间戳转换为相对时间
   const relativeDate = (time) => {
      let now = new Date().getTime();
      let diff = now - time;
      if (diff < 60 * 1000) {
         return "刚刚";
      } else if (diff < 60 * 60 * 1000) {
         return `${Math.floor(diff / 60 / 1000)}分钟前`;
      } else if (diff < 24 * 60 * 60 * 1000) {
         return `${Math.floor(diff / 60 / 60 / 1000)}小时前`;
      } else if (diff < 7 * 24 * 60 * 60 * 1000) {
         return `${Math.floor(diff / 24 / 60 / 60 / 1000)}天前`;
      } else if (diff < 365 * 24 * 60 * 60 * 1000) {
         return `${Math.floor(diff / 7 / 24 / 60 / 60 / 1000)}周前`;
      } else {
         return `${Math.floor(diff / 365 / 24 / 60 / 60 / 1000)}年前`;
      }
   };
   //定义变量控制消息的已读
   const [Badgecontent, setBadgeContent] = useState(Badge.dot);
   const navigate = useNavigate();
   // 获取当前用户id
   const [userId, setUserId] = useState(sessionStorage.getItem("result") ? JSON.parse(sessionStorage.getItem("result"))._id : "");
   console.log(userId);
   // 定义用户userId和friendId的状态
   const [user, setUser] = useState({});
   const [noticeList, setNoticesList] = useState([]);
   let getNotices = async () => {
      try {
         const { result, code } = await getApi({ url: "/Notice/notice" })
         console.log(result, code);
         setNoticesList(result)
      }
      catch (error) {
         console.error("公告错误", error);
      }
   }

   const formatDate = (isoString) => {
      const date = new Date(isoString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从 0 开始的  
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0'); // 获取小时并补零  
      const minutes = String(date.getMinutes()).padStart(2, '0'); // 获取分钟并补零  
      const seconds = String(date.getSeconds()).padStart(2, '0'); // 获取秒数并补零  

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
   };
   /*-----------------------------------------------------*/
   const [ws, setWs] = useState(null);
   const [isConnected, setIsConnected] = useState(false);
   useEffect(() => {
      const webSocket = new WebSocket("ws://127.0.0.1:3000");
      setWs(webSocket);
      console.log(webSocket);
      webSocket.addEventListener("open", () => {
         console.log("WebSocket 连接已打开");
         setIsConnected(true);
      });

      webSocket.addEventListener("error", (error) => {
         console.error("WebSocket 错误:", error);
      });

      webSocket.addEventListener("close", () => {
         console.log("WebSocket 连接已关闭");
         setIsConnected(false);
      });

      webSocket.onmessage = (event) => {
         try {
            const message = event.data;
            if (typeof message !== "string") {
               console.error("消息不是字符串:", message);
               return;
            }
            const parsedMessage = JSON.parse(message);
            const { type, content } = parsedMessage;

            switch (type) {
               case "Notices":
                  console.log("公告消息:", content);
                  getNotices();
                  alert('有一条新公告')
                  break;
               case "heartbeat":
                  console.log("心跳消息:", content);
                  break;
               case "reminding":
                  console.log("消息更新:", content);
                  break;
               default:
                  console.warn("无效的消息类型:", type);
                  break;
            }
         } catch (error) {
            console.error("解析消息时出错:", error);
         }
      };

      return () => {
         webSocket.close();
      };
   }, []);


   useEffect(() => {
      getMessage()
      getNotices()
   }, [])
   // 获取聊天消息的函数
   const getMessage = async () => {
      try {
         const { code, result } = await getApi({
            url: "/user/userId",
            params: { userId }
         })
         if (code === 200) {
            setUser(result)
         } else {
            navigate("/login");
         }
      } catch (error) {
         console.error("获取聊天信息失败：" + error);
      }
   }
   return (<>
      <div className='message'>
         <div className='message-body'>
            <div className='message-body-List'>
               <div>
                  {noticeList.map((i) => {
                     return <div key={i._id}>
                        <p>{i.title}</p>
                        <p>{i.content}</p>
                        <p>{formatDate(i.time)}</p>
                     </div>
                  })}
               </div>
               {user.friends?.map((friend) => (
                  <div
                     key={friend._id}
                     className='message-body-List-item'
                     onClick={() =>
                        navigate("/chatroom", {
                           state: { userId: userId, friendId: friend._id, username: user.username, friendName: friend.username },
                        })
                     }
                  >
                     <div style={{ display: "flex", alignItems: "center", marginLeft: "20px" }}>
                        <Badge content={Badgecontent} style={{ marginTop: "10px" }}>
                           <div className='message-body-List-item-icon'>
                              <div>
                                 <img style={{ borderRadius: "50px", width: "100px", height: "100px" }} src={friend.avatar} alt='' />
                              </div>
                           </div>
                        </Badge>
                        <div style={{ marginLeft: "20px", marginTop: "10px", padding: "8px 0", boxSizing: "border-box" }}>
                           <p className='message-body-List-item-text1'>{friend.username}</p>
                           <p className='message-body-List-item-text'>[游记消息]</p>
                        </div>
                     </div>
                     <div style={{ width: "20%" }}>
                        <p className='message-body-List-item-time'>{relativeDate(Newtime)}</p>
                     </div>
                  </div>
               ))}
            </div>
         </div>
         <div className='message-footer'></div>
      </div>
   </>);
}

export default Message;